<!DOCTYPE HTML>
<html lang="zh-CN">


<head>
    <meta charset="utf-8">
    <meta name="keywords" content="分布式ID, 博客 blog">
    <meta name="description" content="熊猫小二的博客  xmxe&#39;s blog">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <!-- 为了引用qq空间图床文件 -->
    <meta name="referrer" content="no-referrer">
    <!-- Global site tag (gtag.js) - Google Analytics -->


    <title>分布式ID | 熊猫小二</title>
    <link rel="icon" type="image/x-icon, image/vnd.microsoft.icon" href="/blog/favicon.ico">
    <link rel="stylesheet" type="text/css" href="/blog/libs/awesome/css/all.css">
    <link rel="stylesheet" type="text/css" href="/blog/libs/materialize/materialize.min.css">
    <link rel="stylesheet" type="text/css" href="/blog/libs/aos/aos.css">
    <link rel="stylesheet" type="text/css" href="/blog/libs/animate/animate.min.css">
    <link rel="stylesheet" type="text/css" href="/blog/libs/lightGallery/css/lightgallery.min.css">
    <link rel="stylesheet" type="text/css" href="/blog/css/matery.css">
    <link rel="stylesheet" type="text/css" href="/blog/css/my.css">
    <link rel="stylesheet" type="text/css" href="/blog/css/loading.css">

    <script src="/blog/libs/jquery/jquery.min.js"></script>

<meta name="generator" content="Hexo 6.3.0"></head>



   
<style>
    body{
       background-image: url(/blog/medias/cover.jpg);
       background-repeat:no-repeat;
       background-size:cover;
       background-attachment:fixed;
    }
</style>



<body>
    
  <div id="loading-box">
    <div class="loading-left-bg"></div>
    <div class="loading-right-bg"></div>
    <div class="spinner-box">
      <div class="configure-border-1">
        <div class="configure-core"></div>
      </div>
      <div class="configure-border-2">
        <div class="configure-core"></div>
      </div>
      <div class="loading-word">加载中...</div>
    </div>
  </div>
  <!-- 页面加载动画 -->
  <script>
    $(document).ready(function () {
      // document.body.style.overflow = 'auto';
      document.getElementById('loading-box').classList.add("loaded")
    })
  </script>

    <header class="navbar-fixed">
    <nav id="headNav" class="bg-color nav-transparent">
        <div id="navContainer" class="nav-wrapper container">
            <div class="brand-logo">
                <a href="/blog/" class="waves-effect waves-light">
                    
                        <img src="/blog/medias/logo.png" class="logo-img" alt="LOGO">
                    
                    <span class="logo-span">熊猫小二</span>
                </a>
            </div>
            

<a href="#" data-target="mobile-nav" class="sidenav-trigger button-collapse"><i class="fas fa-bars"></i></a>
<ul class="right nav-menu">
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/blog/" class="waves-effect waves-light">
      
      <i class="fas fa-home" style="zoom: 0.6;"></i>
      
      <span>首页</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="#" class="waves-effect waves-light">

      
      <i class="fas fa-book" style="zoom: 0.6;"></i>
      
      <span>归档</span>
      <i class="fas fa-chevron-down" aria-hidden="true" style="zoom: 0.6;"></i>
    </a>
    <ul class="sub-nav menus_item_child ">
      
      <li>
        <a href="/blog/archives">
          
          <i class="fas fa-archive" style="margin-top: -20px; zoom: 0.6;"></i>
          
          <span>归档</span>
        </a>
      </li>
      
      <li>
        <a href="/blog/tags">
          
          <i class="fas fa-tags" style="margin-top: -20px; zoom: 0.6;"></i>
          
          <span>标签</span>
        </a>
      </li>
      
      <li>
        <a href="/blog/categories">
          
          <i class="fas fa-bookmark" style="margin-top: -20px; zoom: 0.6;"></i>
          
          <span>分类</span>
        </a>
      </li>
      
    </ul>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/blog/friends" class="waves-effect waves-light">
      
      <i class="fas fa-address-book" style="zoom: 0.6;"></i>
      
      <span>友链</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="#" class="waves-effect waves-light">

      
      <i class="fas fa-user-circle" style="zoom: 0.6;"></i>
      
      <span>关于</span>
      <i class="fas fa-chevron-down" aria-hidden="true" style="zoom: 0.6;"></i>
    </a>
    <ul class="sub-nav menus_item_child ">
      
      <li>
        <a href="/blog/about">
          
          <i class="fas fa-star-of-david" style="margin-top: -20px; zoom: 0.6;"></i>
          
          <span>主页</span>
        </a>
      </li>
      
      <li>
        <a href="/blog/gallery">
          
          <i class="fas fa-images" style="margin-top: -20px; zoom: 0.6;"></i>
          
          <span>相册</span>
        </a>
      </li>
      
    </ul>
    
  </li>
  
  <li>
    <a href="#searchModal" class="modal-trigger waves-effect waves-light">
      <i id="searchIcon" class="fas fa-search" title="搜索" style="zoom: 0.85;"></i>
    </a>
  </li>
  
    <li>
      <a class="waves-effect waves-light" onclick="switchNightMode()">
        <i id="sum-moon-icon" class="fas fa-sun" style="zoom:0.65;" title="切换主题"></i>
      </a>
    </li>
  
  
</ul>


<div id="mobile-nav" class="side-nav sidenav">

    <div class="mobile-head bg-color">
        
          <img src="/blog/medias/logo.png" class="logo-img circle responsive-img">
        
        <div class="logo-name">熊猫小二</div>
        <div class="logo-desc">
            
            熊猫小二的博客  xmxe&#39;s blog
            
        </div>
    </div>

    

    <ul class="menu-list mobile-menu-list">
        
        <li class="m-nav-item">
	  
		<a href="/blog/" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-home"></i>
			
			首页
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="javascript:;">
			
				<i class="fa-fw fas fa-book"></i>
			
			归档
			<span class="m-icon"><i class="fas fa-chevron-right"></i></span>
		</a>
            <ul  >
              
                <li>

                  <a href="/blog/archives " style="margin-left:75px">
				  
				   <i class="fa fas fa-archive" style="position: absolute;left:50px" ></i>
			      
		          <span>归档</span>
                  </a>
                </li>
              
                <li>

                  <a href="/blog/tags " style="margin-left:75px">
				  
				   <i class="fa fas fa-tags" style="position: absolute;left:50px" ></i>
			      
		          <span>标签</span>
                  </a>
                </li>
              
                <li>

                  <a href="/blog/categories " style="margin-left:75px">
				  
				   <i class="fa fas fa-bookmark" style="position: absolute;left:50px" ></i>
			      
		          <span>分类</span>
                  </a>
                </li>
              
            </ul>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/blog/friends" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-address-book"></i>
			
			友链
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="javascript:;">
			
				<i class="fa-fw fas fa-user-circle"></i>
			
			关于
			<span class="m-icon"><i class="fas fa-chevron-right"></i></span>
		</a>
            <ul  >
              
                <li>

                  <a href="/blog/about " style="margin-left:75px">
				  
				   <i class="fa fas fa-star-of-david" style="position: absolute;left:50px" ></i>
			      
		          <span>主页</span>
                  </a>
                </li>
              
                <li>

                  <a href="/blog/gallery " style="margin-left:75px">
				  
				   <i class="fa fas fa-images" style="position: absolute;left:50px" ></i>
			      
		          <span>相册</span>
                  </a>
                </li>
              
            </ul>
          
        </li>
        
        
    </ul>
</div>


        </div>

        
    </nav>

</header>

    
<script src="/blog/libs/cryptojs/crypto-js.min.js"></script>
<script>
    (function() {
        let pwd = '';
        if (pwd && pwd.length > 0) {
            if (pwd !== CryptoJS.SHA256(prompt('请输入访问本文章的密码')).toString(CryptoJS.enc.Hex)) {
                alert('密码错误，将返回主页！');
                location.href = '/blog/';
            }
        }
    })();
</script>




<div class="bg-cover pd-header post-cover" style="background-image: url('/blog/medias/featureimages/4.jpg')">
    <div class="container" style="right: 0px;left: 0px;">
        <div class="row">
            <div class="col s12 m12 l12">
                <div class="brand">
                    <h1 id="post-title" class="description center-align post-title"></h1>

                    
                        <!-- <script src="https://cdn.jsdelivr.net/npm/typed.js@2.0.11"></script> -->
                        <script>
                            var typedObj = new Typed("#post-title", {
                                strings: [ '分布式ID' ],
                                startDelay: 300,
                                typeSpeed: 70,
                                loop: false,
                                backSpeed: 50,
                                showCursor: true
                            });
                        </script>
                    
                </div>
            </div>
        </div>
    </div>
</div>




<main class="post-container content">

    
    <link rel="stylesheet" href="/blog/libs/tocbot/tocbot.css">
<style>
    #articleContent h1::before,
    #articleContent h2::before,
    #articleContent h3::before,
    #articleContent h4::before,
    #articleContent h5::before,
    #articleContent h6::before {
        display: block;
        content: " ";
        height: 100px;
        margin-top: -100px;
        visibility: hidden;
    }

    #articleContent :focus {
        outline: none;
    }

    .toc-fixed {
        position: fixed;
        top: 64px;
    }

    .toc-widget {
        width: 345px;
        padding-left: 20px;
        background-color: rgb(255, 255, 255,0.7);
        border-radius: 10px;
        box-shadow: 0 10px 35px 2px rgba(0, 0, 0, .15), 0 5px 15px rgba(0, 0, 0, .07), 0 2px 5px -5px rgba(0, 0, 0, .1) !important;
    }

    .toc-widget .toc-title {
        padding: 35px 0 15px 17px;
        font-size: 1.5rem;
        font-weight: bold;
        line-height: 1.5rem;
    }

    .toc-widget ol {
        padding: 0;
        list-style: none;
    }

    #toc-content {
        padding-bottom: 30px;
        overflow: auto;
        max-height: 480px;
    }

    #toc-content ol {
        padding-left: 10px;
    }

    #toc-content ol li {
        padding-left: 10px;
    }

    #toc-content .toc-link:hover {
        color: #42b983;
        font-weight: 700;
        text-decoration: underline;
    }

    #toc-content .toc-link::before {
        background-color: transparent;
        max-height: 25px;

        position: absolute;
        right: 23.5vw;
        display: block;
    }

    #toc-content .is-active-link {
        color: #42b983;
    }

    #floating-toc-btn {
        position: fixed;
        right: 15px;
        bottom: 76px;
        padding-top: 15px;
        margin-bottom: 0;
        z-index: 998;
    }

    #floating-toc-btn .btn-floating {
        width: 48px;
        height: 48px;
    }

    #floating-toc-btn .btn-floating i {
        line-height: 48px;
        font-size: 1.4rem;
    }
</style>
<div class="row">
    <div id="main-content" class="col s12 m12 l9">
        <!-- 文章内容详情 -->
<div id="artDetail">
    <div class="card">
        <div class="card-content article-info">
            <div class="row tag-cate">
                <div class="col s7">
                    
                    <div class="article-tag">
                        
                            <a href="/blog/tags/%E4%BB%A3%E7%A0%81%E5%AE%9E%E6%88%98/">
                                <span class="chip bg-color">代码实战</span>
                            </a>
                        
                    </div>
                    
                </div>
                <div class="col s5 right-align">
                    
                </div>
            </div>

            <div class="post-info">
                

                

                

                

                
            </div>
        </div>
        <hr class="clearfix">

        
        <!-- 是否加载使用自带的 prismjs. -->
        <link rel="stylesheet" href="/blog/libs/prism/prism.css">
        

        
        <!-- 代码块折行 -->
        <style type="text/css">
            code[class*="language-"], pre[class*="language-"] { white-space: pre-wrap !important; }
        </style>
        

        <div class="card-content article-card-content">
            <div id="articleContent">
                <h2 id="分布式ID介绍"><a href="#分布式ID介绍" class="headerlink" title="分布式ID介绍"></a>分布式ID介绍</h2><h3 id="什么是ID？"><a href="#什么是ID？" class="headerlink" title="什么是ID？"></a>什么是ID？</h3><p>日常开发中，我们需要对系统中的各种数据使用ID唯一表示，比如用户ID对应且仅对应一个人，商品ID对应且仅对应一件商品，订单ID对应且仅对应一个订单。我们现实生活中也有各种ID，比如身份证ID对应且仅对应一个人、地址ID对应且仅对应一个地址。简单来说，ID就是数据的唯一标识。</p>
<h3 id="什么是分布式ID？"><a href="#什么是分布式ID？" class="headerlink" title="什么是分布式ID？"></a>什么是分布式ID？</h3><p>分布式ID是分布式系统下的ID。分布式ID不存在与现实生活中，属于计算机系统中的一个概念。简单举一个分库分表的例子。我司的一个项目，使用的是单机MySQL。但是，没想到的是，项目上线一个月之后，随着使用人数越来越多，整个系统的数据量将越来越大。单机MySQL已经没办法支撑了，需要进行分库分表（推荐Sharding-JDBC）。在分库之后，数据遍布在不同服务器上的数据库，数据库的自增主键已经没办法满足生成的主键唯一了。我们如何为不同的数据节点生成全局唯一主键呢？这个时候就需要生成分布式ID了。</p>
<p><img src="https://oss.javaguide.cn/github/javaguide/system-design/distributed-system/id-after-the-sub-table-not-conflict.png" alt="img"></p>
<h3 id="分布式ID需要满足哪些要求"><a href="#分布式ID需要满足哪些要求" class="headerlink" title="分布式ID需要满足哪些要求?"></a>分布式ID需要满足哪些要求?</h3><p><img src="https://oss.javaguide.cn/github/javaguide/system-design/distributed-system/distributed-id-requirements.png" alt="img"></p>
<p>分布式ID作为分布式系统中必不可少的一环，很多地方都要用到分布式ID。一个最基本的分布式ID需要满足下面这些要求：</p>
<ul>
<li><strong>全局唯一</strong>：ID的全局唯一性肯定是首先要满足的！</li>
<li><strong>高性能</strong>：分布式ID的生成速度要快，对本地资源消耗要小。</li>
<li><strong>高可用</strong>：生成分布式ID的服务要保证可用性无限接近于100%。</li>
<li><strong>方便易用</strong>：拿来即用，使用方便，快速接入！</li>
</ul>
<p>除了这些之外，一个比较好的分布式ID还应保证：</p>
<ul>
<li><strong>安全</strong>：ID中不包含敏感信息。</li>
<li><strong>有序递增</strong>：如果要把ID存放在数据库的话，ID的有序性可以提升数据库写入速度。并且，很多时候，我们还很有可能会直接通过ID来进行排序。</li>
<li><strong>有具体的业务含义</strong>：生成的ID如果能有具体的业务含义，可以让定位问题以及开发更透明化（通过ID就能确定是哪个业务）。</li>
<li><strong>独立部署</strong>：也就是分布式系统单独有一个发号器服务，专门用来生成分布式ID。这样就生成ID的服务可以和业务相关的服务解耦。不过，这样同样带来了网络调用消耗增加的问题。总的来说，如果需要用到分布式ID的场景比较多的话，独立部署的发号器服务还是很有必要的。</li>
</ul>
<h2 id="分布式ID常见解决方案"><a href="#分布式ID常见解决方案" class="headerlink" title="分布式ID常见解决方案"></a>分布式ID常见解决方案</h2><h3 id="数据库"><a href="#数据库" class="headerlink" title="数据库"></a>数据库</h3><h4 id="数据库主键自增"><a href="#数据库主键自增" class="headerlink" title="数据库主键自增"></a>数据库主键自增</h4><p>这种方式就比较简单直白了，就是通过关系型数据库的自增主键产生来唯一的ID。</p>
<p><img src="https://oss.javaguide.cn/github/javaguide/system-design/distributed-system/the-primary-key-of-the-database-increases-automatically.png" alt="数据库主键自增"></p>
<p>以MySQL举例，我们通过下面的方式即可。</p>
<p><strong>1.创建一个数据库表。</strong></p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token keyword">CREATE</span> <span class="token keyword">TABLE</span> sequence_id <span class="token punctuation">(</span>
  id <span class="token keyword">bigint</span><span class="token punctuation">(</span><span class="token number">20</span><span class="token punctuation">)</span> <span class="token keyword">unsigned</span> <span class="token operator">NOT</span> <span class="token boolean">NULL</span> <span class="token keyword">AUTO_INCREMENT</span><span class="token punctuation">,</span>
  stub <span class="token keyword">char</span><span class="token punctuation">(</span><span class="token number">10</span><span class="token punctuation">)</span> <span class="token operator">NOT</span> <span class="token boolean">NULL</span> <span class="token keyword">DEFAULT</span> <span class="token string">''</span><span class="token punctuation">,</span>
  <span class="token keyword">PRIMARY</span> <span class="token keyword">KEY</span> <span class="token punctuation">(</span>id<span class="token punctuation">)</span><span class="token punctuation">,</span>
  <span class="token keyword">UNIQUE</span> <span class="token keyword">KEY</span> stub <span class="token punctuation">(</span>stub<span class="token punctuation">)</span>
<span class="token punctuation">)</span> <span class="token keyword">ENGINE</span><span class="token operator">=</span><span class="token keyword">InnoDB</span> <span class="token keyword">DEFAULT</span> <span class="token keyword">CHARSET</span><span class="token operator">=</span>utf8mb4<span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>stub字段无意义，只是为了占位，便于我们插入或者修改数据。并且，给stub字段创建了唯一索引，保证其唯一性。</p>
<p><strong>2.通过replace into来插入数据。</strong></p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token constant">BEGIN</span><span class="token punctuation">;</span>
<span class="token constant">REPLACE</span> <span class="token class-name">INTO</span> sequence_id <span class="token punctuation">(</span>stub<span class="token punctuation">)</span> <span class="token constant">VALUES</span> <span class="token punctuation">(</span><span class="token char">'stub'</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token class-name">SELECT</span> <span class="token function">LAST_INSERT_ID</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token constant">COMMIT</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>

<p>插入数据这里，我们没有使用insert into而是使用replace into来插入数据，具体步骤是这样的：</p>
<ol>
<li><p>第一步：尝试把数据插入到表中。</p>
</li>
<li><p>第二步：如果主键或唯一索引字段出现重复数据错误而插入失败时，先从表中删除含有重复关键字值的冲突行，然后再次尝试把数据插入到表中。</p>
</li>
</ol>
<p>这种方式的优缺点也比较明显：</p>
<ul>
<li><strong>优点</strong>：实现起来比较简单、ID有序递增、存储消耗空间小</li>
<li><strong>缺点</strong>：支持的并发量不大、存在数据库单点问题（可以使用数据库集群解决，不过增加了复杂度）、ID没有具体业务含义、安全问题（比如根据订单ID的递增规律就能推算出每天的订单量，商业机密啊！）、每次获取ID都要访问一次数据库（增加了对数据库的压力，获取速度也慢）</li>
</ul>
<h4 id="数据库号段模式"><a href="#数据库号段模式" class="headerlink" title="数据库号段模式"></a>数据库号段模式</h4><p>数据库主键自增这种模式，每次获取ID都要访问一次数据库，ID需求比较大的时候，肯定是不行的。如果我们可以批量获取，然后存在在内存里面，需要用到的时候，直接从内存里面拿就舒服了！这也就是我们说的基于数据库的号段模式来生成分布式ID。数据库的号段模式也是目前比较主流的一种分布式ID生成方式。像滴滴开源的<a target="_blank" rel="noopener" href="https://github.com/didi/tinyid/wiki/tinyid%E5%8E%9F%E7%90%86%E4%BB%8B%E7%BB%8D">Tinyid</a>就是基于这种方式来做的。不过，TinyId使用了双号段缓存、增加多db支持等方式来进一步优化。以MySQL举例，我们通过下面的方式即可。</p>
<p><strong>1.创建一个数据库表。</strong></p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token keyword">CREATE</span> <span class="token keyword">TABLE</span> sequence_id_generator <span class="token punctuation">(</span>
  id <span class="token keyword">int</span><span class="token punctuation">(</span><span class="token number">10</span><span class="token punctuation">)</span> <span class="token operator">NOT</span> <span class="token boolean">NULL</span><span class="token punctuation">,</span>
  current_max_id <span class="token keyword">bigint</span><span class="token punctuation">(</span><span class="token number">20</span><span class="token punctuation">)</span> <span class="token operator">NOT</span> <span class="token boolean">NULL</span> <span class="token keyword">COMMENT</span> <span class="token string">'当前最大id'</span><span class="token punctuation">,</span>
  step <span class="token keyword">int</span><span class="token punctuation">(</span><span class="token number">10</span><span class="token punctuation">)</span> <span class="token operator">NOT</span> <span class="token boolean">NULL</span> <span class="token keyword">COMMENT</span> <span class="token string">'号段的长度'</span><span class="token punctuation">,</span>
  version <span class="token keyword">int</span><span class="token punctuation">(</span><span class="token number">20</span><span class="token punctuation">)</span> <span class="token operator">NOT</span> <span class="token boolean">NULL</span> <span class="token keyword">COMMENT</span> <span class="token string">'版本号'</span><span class="token punctuation">,</span>
  biz_type <span class="token keyword">int</span><span class="token punctuation">(</span><span class="token number">20</span><span class="token punctuation">)</span> <span class="token operator">NOT</span> <span class="token boolean">NULL</span> <span class="token keyword">COMMENT</span> <span class="token string">'业务类型'</span><span class="token punctuation">,</span>
  <span class="token keyword">PRIMARY</span> <span class="token keyword">KEY</span> <span class="token punctuation">(</span>id<span class="token punctuation">)</span>
<span class="token punctuation">)</span> <span class="token keyword">ENGINE</span><span class="token operator">=</span><span class="token keyword">InnoDB</span> <span class="token keyword">DEFAULT</span> <span class="token keyword">CHARSET</span><span class="token operator">=</span>utf8mb4<span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>current_max_id字段和step字段主要用于获取批量ID，获取的批量id为：current_max_id~current_max_id+step。</p>
<p><img src="https://oss.javaguide.cn/github/javaguide/system-design/distributed-system/database-number-segment-mode.png" alt="数据库号段模式"></p>
<p>version字段主要用于解决并发问题（乐观锁）,biz_type主要用于表示业务类型。</p>
<p><strong>2.先插入一行数据。</strong></p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token keyword">INSERT</span> <span class="token keyword">INTO</span> sequence_id_generator <span class="token punctuation">(</span>id<span class="token punctuation">,</span> current_max_id<span class="token punctuation">,</span> step<span class="token punctuation">,</span> version<span class="token punctuation">,</span> biz_type<span class="token punctuation">)</span>
<span class="token keyword">VALUES</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">,</span> <span class="token number">0</span><span class="token punctuation">,</span> <span class="token number">100</span><span class="token punctuation">,</span> <span class="token number">0</span><span class="token punctuation">,</span> <span class="token number">101</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>

<p><strong>3.通过SELECT获取指定业务下的批量唯一ID</strong></p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token keyword">SELECT</span> current_max_id<span class="token punctuation">,</span> step<span class="token punctuation">,</span>version <span class="token keyword">FROM</span> sequence_id_generator <span class="token keyword">where</span> biz_type <span class="token operator">=</span> <span class="token number">101</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<p>结果：</p>
<pre class="line-numbers language-text" data-language="text"><code class="language-text">id	current_max_id	step	version	biz_type
1	0	100	0	101<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>

<p><strong>4.不够用的话，更新之后重新SELECT即可。</strong></p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token keyword">UPDATE</span> sequence_id_generator <span class="token keyword">SET</span> current_max_id <span class="token operator">=</span> <span class="token number">0</span><span class="token operator">+</span><span class="token number">100</span><span class="token punctuation">,</span> version<span class="token operator">=</span>version<span class="token operator">+</span><span class="token number">1</span> <span class="token keyword">WHERE</span> version <span class="token operator">=</span> <span class="token number">0</span>  <span class="token operator">AND</span> biz_type <span class="token operator">=</span> <span class="token number">101</span>
<span class="token keyword">SELECT</span> current_max_id<span class="token punctuation">,</span> step<span class="token punctuation">,</span>version <span class="token keyword">FROM</span> sequence_id_generator <span class="token keyword">where</span> biz_type <span class="token operator">=</span> <span class="token number">101</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>

<p>结果：</p>
<pre class="line-numbers language-text" data-language="text"><code class="language-text">id	current_max_id	step	version	biz_type
1	100	100	1	101<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>

<p>相比于数据库主键自增的方式，数据库的号段模式对于数据库的访问次数更少，数据库压力更小。另外，为了避免单点问题，你可以从使用主从模式来提高可用性。</p>
<p><strong>数据库号段模式的优缺点:</strong></p>
<ul>
<li><strong>优点</strong>：ID有序递增、存储消耗空间小</li>
<li><strong>缺点</strong>：存在数据库单点问题（可以使用数据库集群解决，不过增加了复杂度）、ID没有具体业务含义、安全问题（比如根据订单ID的递增规律就能推算出每天的订单量，商业机密啊！）</li>
</ul>
<h4 id="NoSQL"><a href="#NoSQL" class="headerlink" title="NoSQL"></a>NoSQL</h4><p><img src="https://oss.javaguide.cn/github/javaguide/system-design/distributed-system/nosql-distributed-id.png" alt="img"></p>
<p>一般情况下，NoSQL方案使用Redis多一些。我们通过Redis的incr命令即可实现对id原子顺序递增。</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> <span class="token builtin class-name">set</span> sequence_id_biz_type <span class="token number">1</span>
OK
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> incr sequence_id_biz_type
<span class="token punctuation">(</span>integer<span class="token punctuation">)</span> <span class="token number">2</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> get sequence_id_biz_type
<span class="token string">"2"</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>为了提高可用性和并发，我们可以使用Redis Cluster。Redis Cluster是Redis官方提供的Redis集群解决方案（3.0+版本）。除了Redis Cluster之外，你也可以使用开源的Redis集群方案<a target="_blank" rel="noopener" href="https://github.com/CodisLabs/codis">Codis</a>（大规模集群比如上百个节点的时候比较推荐）。</p>
<p>除了高可用和并发之外，我们知道Redis基于内存，我们需要持久化数据，避免重启机器或者机器故障后数据丢失。Redis支持两种不同的持久化方式：<strong>快照（snapshotting，RDB）</strong>、<strong>只追加文件（append-onlyfile,AOF）</strong>。并且，Redis4.0开始支持<strong>RDB和AOF的混合持久化</strong>（默认关闭，可以通过配置项aof-use-rdb-preamble开启）。</p>
<p><strong>Redis方案的优缺点：</strong></p>
<ul>
<li><strong>优点</strong>：性能不错并且生成的ID是有序递增的</li>
<li><strong>缺点</strong>：和数据库主键自增方案的缺点类似</li>
</ul>
<p>除了Redis之外，<strong>MongoDB ObjectId</strong>经常也会被拿来当做分布式ID的解决方案。</p>
<p><img src="https://oss.javaguide.cn/github/javaguide/system-design/distributed-system/mongodb9-objectId-distributed-id.png" alt="img"></p>
<p><strong>MongoDB ObjectId</strong>一共需要12个字节存储：</p>
<ul>
<li>0~3：时间戳</li>
<li>3~6：代表机器ID</li>
<li>7~8：机器进程ID</li>
<li>9~11：自增值</li>
</ul>
<p><strong>MongoDB方案的优缺点：</strong></p>
<ul>
<li><strong>优点</strong>：性能不错并且生成的ID是有序递增的</li>
<li><strong>缺点</strong>：需要解决重复ID问题（当机器时间不对的情况下，可能导致会产生重复ID）、有安全性问题（ID生成有规律性）</li>
</ul>
<h3 id="算法"><a href="#算法" class="headerlink" title="算法"></a>算法</h3><h4 id="UUID"><a href="#UUID" class="headerlink" title="UUID"></a>UUID</h4><p>UUID是Universally Unique Identifier（通用唯一标识符）的缩写。UUID包含32个16进制数字（8-4-4-4-12）。JDK就提供了现成的生成UUID的方法，一行代码就行了。</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token comment">//输出示例：cb4a9ede-fa5e-4585-b9bb-d60bce986eaa</span>
<span class="token constant">UUID</span><span class="token punctuation">.</span><span class="token function">randomUUID</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>

<p><a target="_blank" rel="noopener" href="https://tools.ietf.org/html/rfc4122">RFC 4122</a>中关于UUID的示例是这样的：</p>
<p><img src="https://oss.javaguide.cn/github/javaguide/system-design/distributed-system/rfc-4122-uuid.png" alt="img"></p>
<p>我们这里重点关注一下这个Version(版本)，不同的版本对应的UUID的生成规则是不同的。5种不同的Version(版本)值分别对应的含义（参考<a target="_blank" rel="noopener" href="https://zh.wikipedia.org/wiki/%E9%80%9A%E7%94%A8%E5%94%AF%E4%B8%80%E8%AF%86%E5%88%AB%E7%A0%81">维基百科对于UUID的介绍</a>）：</p>
<ul>
<li><strong>版本1</strong>:UUID是根据时间和节点ID（通常是MAC地址）生成；</li>
<li><strong>版本2</strong>:UUID是根据标识符（通常是组或用户ID）、时间和节点ID生成；</li>
<li><strong>版本3、版本5</strong>:版本5-确定性UUID通过散列（hashing）名字空间（namespace）标识符和名称生成；</li>
<li><strong>版本4</strong>:UUID使用<a target="_blank" rel="noopener" href="https://zh.wikipedia.org/wiki/%E9%9A%8F%E6%9C%BA%E6%80%A7">随机性</a>或<a target="_blank" rel="noopener" href="https://zh.wikipedia.org/wiki/%E4%BC%AA%E9%9A%8F%E6%9C%BA%E6%80%A7">伪随机性</a>生成。</li>
</ul>
<p>下面是Version1版本下生成的UUID的示例：</p>
<p><img src="https://oss.javaguide.cn/github/javaguide/system-design/distributed-system/version1-uuid.png" alt="Version1版本下生成的UUID的示例"></p>
<p>JDK中通过UUID的randomUUID()方法生成的UUID的版本默认为4。</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token class-name">UUID</span> uuid <span class="token operator">=</span> <span class="token constant">UUID</span><span class="token punctuation">.</span><span class="token function">randomUUID</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token keyword">int</span> version <span class="token operator">=</span> uuid<span class="token punctuation">.</span><span class="token function">version</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">//4</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>

<p>另外，Variant(变体)也有4种不同的值，这种值分别对应不同的含义。需要用到的时候，去看看维基百科对于UUID的Variant(变体)相关的介绍即可。</p>
<p>从上面的介绍中可以看出，UUID可以保证唯一性，因为其生成规则包括MAC地址、时间戳、名字空间（Namespace）、随机或伪随机数、时序等元素，计算机基于这些规则生成的UUID是肯定不会重复的。虽然，UUID可以做到全局唯一性，但是，我们一般很少会使用它。比如使用UUID作为MySQL数据库主键的时候就非常不合适：</p>
<ol>
<li><strong>数据库主键要尽量越短越好，而UUID的消耗的存储空间比较大（32个字符串，128位）。</strong></li>
<li><strong>UUID是无顺序的，InnoDB引擎下，数据库主键的无序性会严重影响数据库性能。</strong></li>
</ol>
<p>最后，我们再简单分析一下UUID的优缺点:</p>
<ul>
<li><strong>优点</strong>：生成速度比较快、简单易用</li>
<li><strong>缺点</strong>：存储消耗空间大（32个字符串，128位）、不安全(基于MAC地址生成UUID的算法会造成MAC地址泄露)、无序（非自增）、没有具体业务含义、需要解决重复ID问题（当机器时间不对的情况下，可能导致会产生重复ID）</li>
</ul>
<h4 id="Snowflake-雪花算法"><a href="#Snowflake-雪花算法" class="headerlink" title="Snowflake(雪花算法)"></a>Snowflake(雪花算法)</h4><p>Snowflake是Twitter开源的分布式ID生成算法。Snowflake由64bit的二进制数字组成，这64bit的二进制被分成了几部分，每一部分存储的数据都有特定的含义：</p>
<ul>
<li><strong>第0位</strong>：符号位（标识正负），始终为0，没有用，不用管。</li>
<li><strong>第1~41位</strong>：一共41位，用来表示时间戳，单位是毫秒，可以支撑2^41毫秒（约69年）</li>
<li><strong>第42~52位</strong>：一共10位，一般来说，前5位表示机房ID，后5位表示机器ID（实际项目中可以根据实际情况调整）。这样就可以区分不同集群&#x2F;机房的节点。</li>
<li><strong>第53~64位</strong>：一共12位，用来表示序列号。序列号为自增值，代表单台机器每毫秒能够产生的最大ID数(2^12&#x3D;4096),也就是说单台机器每毫秒最多可以生成4096个唯一ID。</li>
</ul>
<p><img src="https://oss.javaguide.cn/github/javaguide/system-design/distributed-system/snowflake-distributed-id-schematic-diagram.png" alt="Snowflake示意图"></p>
<p>如果你想要使用Snowflake算法的话，一般不需要你自己再造轮子。有很多基于Snowflake算法的开源实现比如美团的Leaf、百度的UidGenerator，并且这些开源实现对原有的Snowflake算法进行了优化。另外，在实际项目中，我们一般也会对Snowflake算法进行改造，最常见的就是在Snowflake算法生成的ID中加入业务类型信息。</p>
<p>我们再来看看Snowflake算法的优缺点：</p>
<ul>
<li><strong>优点</strong>：生成速度比较快、生成的ID有序递增、比较灵活（可以对Snowflake算法进行简单的改造比如加入业务ID）</li>
<li><strong>缺点</strong>：需要解决重复ID问题（依赖时间，当机器时间不对的情况下，可能导致会产生重复ID）。</li>
</ul>
<p><strong>雪花算法生成分布式ID</strong></p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">SnowFlake</span> <span class="token punctuation">&#123;</span>

    <span class="token comment">/**
     * 起始的时间戳
     */</span>
    <span class="token keyword">private</span> <span class="token keyword">final</span> <span class="token keyword">static</span> <span class="token keyword">long</span> <span class="token constant">START_STMP</span> <span class="token operator">=</span> <span class="token number">1480166465631L</span><span class="token punctuation">;</span>

    <span class="token comment">/**
     * 每一部分占用的位数
     */</span>
    <span class="token keyword">private</span> <span class="token keyword">final</span> <span class="token keyword">static</span> <span class="token keyword">long</span> <span class="token constant">SEQUENCE_BIT</span> <span class="token operator">=</span> <span class="token number">12</span><span class="token punctuation">;</span> <span class="token comment">// 序列号占用的位数</span>
    <span class="token keyword">private</span> <span class="token keyword">final</span> <span class="token keyword">static</span> <span class="token keyword">long</span> <span class="token constant">MACHINE_BIT</span> <span class="token operator">=</span> <span class="token number">5</span><span class="token punctuation">;</span> <span class="token comment">// 机器标识占用的位数</span>
    <span class="token keyword">private</span> <span class="token keyword">final</span> <span class="token keyword">static</span> <span class="token keyword">long</span> <span class="token constant">DATACENTER_BIT</span> <span class="token operator">=</span> <span class="token number">5</span><span class="token punctuation">;</span><span class="token comment">// 数据中心占用的位数</span>

    <span class="token comment">/**
     * 每一部分的最大值
     */</span>
    <span class="token keyword">private</span> <span class="token keyword">final</span> <span class="token keyword">static</span> <span class="token keyword">long</span> <span class="token constant">MAX_DATACENTER_NUM</span> <span class="token operator">=</span> <span class="token operator">-</span><span class="token number">1L</span> <span class="token operator">^</span> <span class="token punctuation">(</span><span class="token operator">-</span><span class="token number">1L</span> <span class="token operator">&lt;&lt;</span> <span class="token constant">DATACENTER_BIT</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">private</span> <span class="token keyword">final</span> <span class="token keyword">static</span> <span class="token keyword">long</span> <span class="token constant">MAX_MACHINE_NUM</span> <span class="token operator">=</span> <span class="token operator">-</span><span class="token number">1L</span> <span class="token operator">^</span> <span class="token punctuation">(</span><span class="token operator">-</span><span class="token number">1L</span> <span class="token operator">&lt;&lt;</span> <span class="token constant">MACHINE_BIT</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">private</span> <span class="token keyword">final</span> <span class="token keyword">static</span> <span class="token keyword">long</span> <span class="token constant">MAX_SEQUENCE</span> <span class="token operator">=</span> <span class="token operator">-</span><span class="token number">1L</span> <span class="token operator">^</span> <span class="token punctuation">(</span><span class="token operator">-</span><span class="token number">1L</span> <span class="token operator">&lt;&lt;</span> <span class="token constant">SEQUENCE_BIT</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

    <span class="token comment">/**
     * 每一部分向左的位移
     */</span>
    <span class="token keyword">private</span> <span class="token keyword">final</span> <span class="token keyword">static</span> <span class="token keyword">long</span> <span class="token constant">MACHINE_LEFT</span> <span class="token operator">=</span> <span class="token constant">SEQUENCE_BIT</span><span class="token punctuation">;</span>
    <span class="token keyword">private</span> <span class="token keyword">final</span> <span class="token keyword">static</span> <span class="token keyword">long</span> <span class="token constant">DATACENTER_LEFT</span> <span class="token operator">=</span> <span class="token constant">SEQUENCE_BIT</span> <span class="token operator">+</span> <span class="token constant">MACHINE_BIT</span><span class="token punctuation">;</span>
    <span class="token keyword">private</span> <span class="token keyword">final</span> <span class="token keyword">static</span> <span class="token keyword">long</span> <span class="token constant">TIMESTMP_LEFT</span> <span class="token operator">=</span> <span class="token constant">DATACENTER_LEFT</span> <span class="token operator">+</span> <span class="token constant">DATACENTER_BIT</span><span class="token punctuation">;</span>

    <span class="token keyword">private</span> <span class="token keyword">long</span> datacenterId<span class="token punctuation">;</span> <span class="token comment">// 数据中心</span>
    <span class="token keyword">private</span> <span class="token keyword">long</span> machineId<span class="token punctuation">;</span> <span class="token comment">// 机器标识</span>
    <span class="token keyword">private</span> <span class="token keyword">long</span> sequence <span class="token operator">=</span> <span class="token number">0L</span><span class="token punctuation">;</span> <span class="token comment">// 序列号</span>
    <span class="token keyword">private</span> <span class="token keyword">long</span> lastStmp <span class="token operator">=</span> <span class="token operator">-</span><span class="token number">1L</span><span class="token punctuation">;</span><span class="token comment">// 上一次时间戳</span>

    <span class="token keyword">public</span> <span class="token class-name">SnowFlake</span><span class="token punctuation">(</span><span class="token keyword">long</span> datacenterId<span class="token punctuation">,</span> <span class="token keyword">long</span> machineId<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span>datacenterId <span class="token operator">></span> <span class="token constant">MAX_DATACENTER_NUM</span> <span class="token operator">||</span> datacenterId <span class="token operator">&lt;</span> <span class="token number">0</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token keyword">throw</span> <span class="token keyword">new</span> <span class="token class-name">IllegalArgumentException</span><span class="token punctuation">(</span><span class="token string">"datacenterId can't be greater than MAX_DATACENTER_NUM or less than 0"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span>machineId <span class="token operator">></span> <span class="token constant">MAX_MACHINE_NUM</span> <span class="token operator">||</span> machineId <span class="token operator">&lt;</span> <span class="token number">0</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token keyword">throw</span> <span class="token keyword">new</span> <span class="token class-name">IllegalArgumentException</span><span class="token punctuation">(</span><span class="token string">"machineId can't be greater than MAX_MACHINE_NUM or less than 0"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>datacenterId <span class="token operator">=</span> datacenterId<span class="token punctuation">;</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>machineId <span class="token operator">=</span> machineId<span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>

    <span class="token comment">/**
     * 产生下一个ID
     *
     * @return
     */</span>
    <span class="token keyword">public</span> <span class="token keyword">synchronized</span> <span class="token keyword">long</span> <span class="token function">nextId</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token keyword">long</span> currStmp <span class="token operator">=</span> <span class="token function">getNewstmp</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span>currStmp <span class="token operator">&lt;</span> lastStmp<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token keyword">throw</span> <span class="token keyword">new</span> <span class="token class-name">RuntimeException</span><span class="token punctuation">(</span><span class="token string">"Clock moved backwards.  Refusing to generate id"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>

        <span class="token keyword">if</span> <span class="token punctuation">(</span>currStmp <span class="token operator">==</span> lastStmp<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token comment">// 相同毫秒内，序列号自增</span>
            sequence <span class="token operator">=</span> <span class="token punctuation">(</span>sequence <span class="token operator">+</span> <span class="token number">1</span><span class="token punctuation">)</span> <span class="token operator">&amp;</span> <span class="token constant">MAX_SEQUENCE</span><span class="token punctuation">;</span>
            <span class="token comment">// 同一毫秒的序列数已经达到最大</span>
            <span class="token keyword">if</span> <span class="token punctuation">(</span>sequence <span class="token operator">==</span> <span class="token number">0L</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                currStmp <span class="token operator">=</span> <span class="token function">getNextMill</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token punctuation">&#125;</span>
        <span class="token punctuation">&#125;</span> <span class="token keyword">else</span> <span class="token punctuation">&#123;</span>
            <span class="token comment">// 不同毫秒内，序列号置为0</span>
            sequence <span class="token operator">=</span> <span class="token number">0L</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>

        lastStmp <span class="token operator">=</span> currStmp<span class="token punctuation">;</span>

        <span class="token keyword">return</span> <span class="token punctuation">(</span>currStmp <span class="token operator">-</span> <span class="token constant">START_STMP</span><span class="token punctuation">)</span> <span class="token operator">&lt;&lt;</span> <span class="token constant">TIMESTMP_LEFT</span> <span class="token comment">// 时间戳部分</span>
                <span class="token operator">|</span> datacenterId <span class="token operator">&lt;&lt;</span> <span class="token constant">DATACENTER_LEFT</span> <span class="token comment">// 数据中心部分</span>
                <span class="token operator">|</span> machineId <span class="token operator">&lt;&lt;</span> <span class="token constant">MACHINE_LEFT</span> <span class="token comment">// 机器标识部分</span>
                <span class="token operator">|</span> sequence<span class="token punctuation">;</span> <span class="token comment">// 序列号部分</span>
    <span class="token punctuation">&#125;</span>

    <span class="token keyword">private</span> <span class="token keyword">long</span> <span class="token function">getNextMill</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token keyword">long</span> mill <span class="token operator">=</span> <span class="token function">getNewstmp</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">while</span> <span class="token punctuation">(</span>mill <span class="token operator">&lt;=</span> lastStmp<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            mill <span class="token operator">=</span> <span class="token function">getNewstmp</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>
        <span class="token keyword">return</span> mill<span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>

    <span class="token keyword">private</span> <span class="token keyword">long</span> <span class="token function">getNewstmp</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token keyword">return</span> <span class="token class-name">System</span><span class="token punctuation">.</span><span class="token function">currentTimeMillis</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>

    <span class="token keyword">public</span> <span class="token keyword">static</span> <span class="token keyword">void</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token class-name">String</span><span class="token punctuation">[</span><span class="token punctuation">]</span> args<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token class-name">SnowFlake</span> snowFlake <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">SnowFlake</span><span class="token punctuation">(</span><span class="token number">2</span><span class="token punctuation">,</span> <span class="token number">3</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token keyword">int</span> i <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span> i <span class="token operator">&lt;</span> <span class="token punctuation">(</span><span class="token number">1</span> <span class="token operator">&lt;&lt;</span> <span class="token number">12</span><span class="token punctuation">)</span><span class="token punctuation">;</span> i<span class="token operator">++</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>snowFlake<span class="token punctuation">.</span><span class="token function">nextId</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>

    <span class="token punctuation">&#125;</span>
<span class="token punctuation">&#125;</span>

<span class="token comment">/**
 * 饿汉式单例模式实现雪花算法
 **/</span>
<span class="token keyword">class</span> <span class="token class-name">SnowFlakeSingleE</span> <span class="token punctuation">&#123;</span>

    <span class="token keyword">private</span> <span class="token keyword">static</span> <span class="token class-name">SnowFlakeSingleE</span> snowFlake <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">SnowFlakeSingleE</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

    <span class="token keyword">private</span> <span class="token class-name">SnowFlakeSingleE</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span>

    <span class="token keyword">public</span> <span class="token keyword">static</span> <span class="token class-name">SnowFlakeSingleE</span> <span class="token function">getInstance</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token keyword">return</span> snowFlake<span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>

    <span class="token comment">// 序列号，同一毫秒内用此参数来控制并发</span>
    <span class="token keyword">private</span> <span class="token keyword">long</span> sequence <span class="token operator">=</span> <span class="token number">0L</span><span class="token punctuation">;</span>
    <span class="token comment">// 上一次生成编号的时间串，格式：yyMMddHHmmssSSS</span>
    <span class="token keyword">private</span> <span class="token class-name">String</span> lastTime <span class="token operator">=</span> <span class="token string">""</span><span class="token punctuation">;</span>

    <span class="token keyword">public</span> <span class="token keyword">synchronized</span> <span class="token class-name">String</span> <span class="token function">getNum</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token class-name">String</span> nowTime <span class="token operator">=</span> <span class="token function">getTime</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token comment">// 获取当前时间串，格式：yyMMddHHmmssSSS</span>
        <span class="token class-name">String</span> machineId <span class="token operator">=</span> <span class="token string">"01"</span><span class="token punctuation">;</span> <span class="token comment">// 机器编号，这里假装获取到的机器编号是2。实际项目中可从配置文件中读取</span>
        <span class="token comment">// 本次和上次不是同一毫秒，直接生成编号返回</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token operator">!</span>lastTime<span class="token punctuation">.</span><span class="token function">equals</span><span class="token punctuation">(</span>nowTime<span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            sequence <span class="token operator">=</span> <span class="token number">0L</span><span class="token punctuation">;</span> <span class="token comment">// 重置序列号，方便下次使用</span>
            lastTime <span class="token operator">=</span> nowTime<span class="token punctuation">;</span> <span class="token comment">// 更新时间串，方便下次使用</span>
            <span class="token keyword">return</span> <span class="token keyword">new</span> <span class="token class-name">StringBuilder</span><span class="token punctuation">(</span>nowTime<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">append</span><span class="token punctuation">(</span>machineId<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">append</span><span class="token punctuation">(</span>sequence<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">toString</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>
        <span class="token comment">// 本次和上次在同一个毫秒内，需要用序列号控制并发</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span>sequence <span class="token operator">&lt;</span> <span class="token number">99</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span> <span class="token comment">// 序列号没有达到最大值，直接生成编号返回</span>
            sequence <span class="token operator">=</span> sequence <span class="token operator">+</span> <span class="token number">1</span><span class="token punctuation">;</span>
            <span class="token keyword">return</span> <span class="token keyword">new</span> <span class="token class-name">StringBuilder</span><span class="token punctuation">(</span>nowTime<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">append</span><span class="token punctuation">(</span>machineId<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">append</span><span class="token punctuation">(</span>sequence<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">toString</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>
        <span class="token comment">// 序列号达到最大值，需要等待下一毫秒的到来</span>
        <span class="token keyword">while</span> <span class="token punctuation">(</span>lastTime<span class="token punctuation">.</span><span class="token function">equals</span><span class="token punctuation">(</span>nowTime<span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            nowTime <span class="token operator">=</span> <span class="token function">getTime</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>
        sequence <span class="token operator">=</span> <span class="token number">0L</span><span class="token punctuation">;</span> <span class="token comment">// 重置序列号，方便下次使用</span>
        lastTime <span class="token operator">=</span> nowTime<span class="token punctuation">;</span> <span class="token comment">// 更新时间串，方便下次使用</span>
        <span class="token keyword">return</span> <span class="token keyword">new</span> <span class="token class-name">StringBuilder</span><span class="token punctuation">(</span>nowTime<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">append</span><span class="token punctuation">(</span>machineId<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">append</span><span class="token punctuation">(</span>sequence<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">toString</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>

    <span class="token keyword">private</span> <span class="token class-name">String</span> <span class="token function">getTime</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token keyword">return</span> <span class="token class-name">LocalDateTime</span><span class="token punctuation">.</span><span class="token function">now</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">format</span><span class="token punctuation">(</span><span class="token class-name">DateTimeFormatter</span><span class="token punctuation">.</span><span class="token function">ofPattern</span><span class="token punctuation">(</span><span class="token string">"yyMMddHHmmssSSS"</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>
<span class="token punctuation">&#125;</span>


<span class="token comment">/**
 * 懒汉式单例模式实现雪花算法
 **/</span>
<span class="token keyword">class</span> <span class="token class-name">SnowFlakeSingleL</span> <span class="token punctuation">&#123;</span>

    <span class="token keyword">private</span> <span class="token keyword">static</span> <span class="token class-name">SnowFlakeSingleL</span> snowFlake <span class="token operator">=</span> <span class="token keyword">null</span><span class="token punctuation">;</span>

    <span class="token keyword">private</span> <span class="token class-name">SnowFlakeSingleL</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span>

    <span class="token keyword">public</span> <span class="token keyword">static</span> <span class="token class-name">SnowFlakeSingleL</span> <span class="token function">getInstance</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span>snowFlake <span class="token operator">==</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token keyword">synchronized</span> <span class="token punctuation">(</span><span class="token class-name">SnowFlakeSingleL</span><span class="token punctuation">.</span><span class="token keyword">class</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                <span class="token keyword">if</span> <span class="token punctuation">(</span>snowFlake <span class="token operator">==</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                    snowFlake <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">SnowFlakeSingleL</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token punctuation">&#125;</span>
                <span class="token keyword">return</span> snowFlake<span class="token punctuation">;</span>
            <span class="token punctuation">&#125;</span>
        <span class="token punctuation">&#125;</span>
        <span class="token keyword">return</span> snowFlake<span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>

    <span class="token comment">// 序列号，同一毫秒内用此参数来控制并发</span>
    <span class="token keyword">private</span> <span class="token keyword">long</span> sequence <span class="token operator">=</span> <span class="token number">0L</span><span class="token punctuation">;</span>
    <span class="token comment">// 上一次生成编号的时间串，格式：yyMMddHHmmssSSS</span>
    <span class="token keyword">private</span> <span class="token class-name">String</span> lastTime <span class="token operator">=</span> <span class="token string">""</span><span class="token punctuation">;</span>

    <span class="token keyword">public</span> <span class="token keyword">synchronized</span> <span class="token class-name">String</span> <span class="token function">getNum</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token class-name">String</span> nowTime <span class="token operator">=</span> <span class="token function">getTime</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token comment">// 获取当前时间串，格式：yyMMddHHmmssSSS</span>
        <span class="token class-name">String</span> machineId <span class="token operator">=</span> <span class="token string">"01"</span><span class="token punctuation">;</span> <span class="token comment">// 机器编号，这里假装获取到的机器编号是2。实际项目中可从配置文件中读取</span>
        <span class="token comment">// 本次和上次不是同一毫秒，直接生成编号返回</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token operator">!</span>lastTime<span class="token punctuation">.</span><span class="token function">equals</span><span class="token punctuation">(</span>nowTime<span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            sequence <span class="token operator">=</span> <span class="token number">0L</span><span class="token punctuation">;</span> <span class="token comment">// 重置序列号，方便下次使用</span>
            lastTime <span class="token operator">=</span> nowTime<span class="token punctuation">;</span> <span class="token comment">// 更新时间串，方便下次使用</span>
            <span class="token keyword">return</span> <span class="token keyword">new</span> <span class="token class-name">StringBuilder</span><span class="token punctuation">(</span>nowTime<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">append</span><span class="token punctuation">(</span>machineId<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">append</span><span class="token punctuation">(</span>sequence<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">toString</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>
        <span class="token comment">// 本次和上次在同一个毫秒内，需要用序列号控制并发</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span>sequence <span class="token operator">&lt;</span> <span class="token number">99</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span> <span class="token comment">// 序列号没有达到最大值，直接生成编号返回</span>
            sequence <span class="token operator">=</span> sequence <span class="token operator">+</span> <span class="token number">1</span><span class="token punctuation">;</span>
            <span class="token keyword">return</span> <span class="token keyword">new</span> <span class="token class-name">StringBuilder</span><span class="token punctuation">(</span>nowTime<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">append</span><span class="token punctuation">(</span>machineId<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">append</span><span class="token punctuation">(</span>sequence<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">toString</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>
        <span class="token comment">// 序列号达到最大值，需要等待下一毫秒的到来</span>
        <span class="token keyword">while</span> <span class="token punctuation">(</span>lastTime<span class="token punctuation">.</span><span class="token function">equals</span><span class="token punctuation">(</span>nowTime<span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            nowTime <span class="token operator">=</span> <span class="token function">getTime</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>
        sequence <span class="token operator">=</span> <span class="token number">0L</span><span class="token punctuation">;</span> <span class="token comment">// 重置序列号，方便下次使用</span>
        lastTime <span class="token operator">=</span> nowTime<span class="token punctuation">;</span> <span class="token comment">// 更新时间串，方便下次使用</span>
        <span class="token keyword">return</span> <span class="token keyword">new</span> <span class="token class-name">StringBuilder</span><span class="token punctuation">(</span>nowTime<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">append</span><span class="token punctuation">(</span>machineId<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">append</span><span class="token punctuation">(</span>sequence<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">toString</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>

    <span class="token keyword">private</span> <span class="token class-name">String</span> <span class="token function">getTime</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token keyword">return</span> <span class="token class-name">LocalDateTime</span><span class="token punctuation">.</span><span class="token function">now</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">format</span><span class="token punctuation">(</span><span class="token class-name">DateTimeFormatter</span><span class="token punctuation">.</span><span class="token function">ofPattern</span><span class="token punctuation">(</span><span class="token string">"yyMMddHHmmssSSS"</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>


<h3 id="开源框架"><a href="#开源框架" class="headerlink" title="开源框架"></a>开源框架</h3><h4 id="UidGenerator-百度"><a href="#UidGenerator-百度" class="headerlink" title="UidGenerator(百度)"></a>UidGenerator(百度)</h4><p><a target="_blank" rel="noopener" href="https://github.com/baidu/uid-generator">UidGenerator</a>是百度开源的一款基于Snowflake(雪花算法)的唯一ID生成器。不过，UidGenerator对Snowflake(雪花算法)进行了改进，生成的唯一ID组成如下。</p>
<p><img src="https://oss.javaguide.cn/github/javaguide/system-design/distributed-system/uidgenerator-distributed-id-schematic-diagram.png" alt="img"></p>
<p>可以看出，和原始Snowflake(雪花算法)生成的唯一ID的组成不太一样。并且，上面这些参数我们都可以自定义。UidGenerator官方文档中的介绍如下：</p>
<p><img src="https://oss.javaguide.cn/github/javaguide/system-design/distributed-system/uidgenerator-introduction-official-documents.png" alt="img"></p>
<p>自18年后，UidGenerator就基本没有再维护了，我这里也不过多介绍。想要进一步了解的朋友，可以看看<a target="_blank" rel="noopener" href="https://github.com/baidu/uid-generator/blob/master/README.zh_cn.md">UidGenerator的官方介绍</a>。</p>
<h4 id="Leaf-美团"><a href="#Leaf-美团" class="headerlink" title="Leaf(美团)"></a>Leaf(美团)</h4><p><a target="_blank" rel="noopener" href="https://github.com/Meituan-Dianping/Leaf">Leaf</a>是美团开源的一个分布式ID解决方案。这个项目的名字Leaf（树叶）起源于德国哲学家、数学家莱布尼茨的一句话：“There are no two identical leaves in the world”（世界上没有两片相同的树叶）。这名字起得真心挺不错的，有点文艺青年那味了！</p>
<p>Leaf提供了<strong>号段模式</strong>和<strong>Snowflake</strong>(雪花算法)这两种模式来生成分布式ID。并且它支持双号段，还解决了雪花ID系统时钟回拨问题。不过，时钟问题的解决需要弱依赖于Zookeeper。Leaf的诞生主要是为了解决美团各个业务线生成分布式ID的方法多种多样以及不可靠的问题。Leaf对原有的号段模式进行改进，比如它这里增加了双号段避免获取DB在获取号段的时候阻塞请求获取ID的线程。简单来说，就是我一个号段还没用完之前，我自己就主动提前去获取下一个号段（图片来自于美团官方文章：<a target="_blank" rel="noopener" href="https://tech.meituan.com/2017/04/21/mt-leaf.html">《Leaf—美团点评分布式ID生成系统》openinnewwindow</a>）。</p>
<p><img src="https://oscimg.oschina.net/oscnet/up-5c152efed042a8fe7e13692e0339d577f5c.png" alt="img"></p>
<p>根据项目README介绍，在4C8GVM基础上，通过公司RPC方式调用，QPS压测结果近5w&#x2F;s，TP9991ms。</p>
<h4 id="Tinyid-滴滴"><a href="#Tinyid-滴滴" class="headerlink" title="Tinyid(滴滴)"></a>Tinyid(滴滴)</h4><p><a target="_blank" rel="noopener" href="https://github.com/didi/tinyid">Tinyid</a>是滴滴开源的一款基于数据库号段模式的唯一ID生成器。数据库号段模式的原理我们在上面已经介绍过了。Tinyid有哪些亮点呢？为了搞清楚这个问题，我们先来看看基于数据库号段模式的简单架构方案。（图片来自于Tinyid的官方wiki:<a target="_blank" rel="noopener" href="https://github.com/didi/tinyid/wiki/tinyid%E5%8E%9F%E7%90%86%E4%BB%8B%E7%BB%8D">《Tinyid原理介绍》</a>）</p>
<p><img src="https://oscimg.oschina.net/oscnet/up-4afc0e45c0c86ba5ad645d023dce11e53c2.png" alt="img"></p>
<p>在这种架构模式下，我们通过HTTP请求向发号器服务申请唯一ID。负载均衡router会把我们的请求送往其中的一台tinyid-server。这种方案有什么问题呢？在我看来（Tinyid官方wiki也有介绍到），主要由下面这2个问题：</p>
<ul>
<li>获取新号段的情况下，程序获取唯一ID的速度比较慢。</li>
<li>需要保证DB高可用，这个是比较麻烦且耗费资源的。</li>
</ul>
<p>除此之外，HTTP调用也存在网络开销。</p>
<p>Tinyid的原理比较简单，其架构如下图所示：</p>
<p><img src="https://oscimg.oschina.net/oscnet/up-53f74cd615178046d6c04fe50513fee74ce.png" alt="img"></p>
<p>相比于基于数据库号段模式的简单架构方案，Tinyid方案主要做了下面这些优化：</p>
<ul>
<li><strong>双号段缓存</strong>：为了避免在获取新号段的情况下，程序获取唯一ID的速度比较慢。Tinyid中的号段在用到一定程度的时候，就会去异步加载下一个号段，保证内存中始终有可用号段。</li>
<li><strong>增加多db支持</strong>：支持多个DB，并且，每个DB都能生成唯一ID，提高了可用性。</li>
<li><strong>增加tinyid-client</strong>：纯本地操作，无HTTP请求消耗，性能和可用性都有很大提升。</li>
</ul>
<p>Tinyid的优缺点这里就不分析了，结合数据库号段模式的优缺点和Tinyid的原理就能知道。</p>
<h2 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h2><p>通过这篇文章，我基本上已经把最常见的分布式ID生成方案都总结了一波。除了上面介绍的方式之外，像ZooKeeper这类中间件也可以帮助我们生成唯一ID。需要结合实际项目来选择最适合自己的方案。</p>
<blockquote>
<p><a target="_blank" rel="noopener" href="https://javaguide.cn/distributed-system/distributed-id.html">原文链接</a></p>
</blockquote>
<table>
<thead>
<tr>
<th align="center"><a target="_blank" rel="noopener" href="https://mp.weixin.qq.com/s/-30WmwoYHg0oWZSWedE5MQ">深度介绍分布式系统原理与设计</a></th>
<th align="center"><a target="_blank" rel="noopener" href="https://mp.weixin.qq.com/s/zXchd2SEjLkHftCe9-2_-Q">一口气说出9种分布式ID生成方式</a></th>
<th align="center"><a target="_blank" rel="noopener" href="https://mp.weixin.qq.com/s/jGq7SvVggZ7gNqM2SZ320Q">七种分布式全局ID生成策略，你更爱哪种</a></th>
</tr>
</thead>
<tbody><tr>
<td align="center"><a target="_blank" rel="noopener" href="https://mp.weixin.qq.com/s/dEkkSCbQzfhH3NuXsbbY0w">一起学习下一线大厂的分布式唯一ID生成方案</a></td>
<td align="center"></td>
<td align="center"></td>
</tr>
</tbody></table>

                
            </div>
            <hr/>

            

    <div class="reprint" id="reprint-statement">
        
            <div class="reprint__author">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-user">
                        文章作者:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="/blog/about" rel="external nofollow noreferrer">xmxe</a>
                </span>
            </div>
            <div class="reprint__type">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-link">
                        文章链接:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="https://xmxe.github.io/blog/posts/50bd139ed1e1/">https://xmxe.github.io/blog/posts/50bd139ed1e1/</a>
                </span>
            </div>
            <div class="reprint__notice">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-copyright">
                        版权声明:
                    </i>
                </span>
                <span class="reprint-info">
                    本博客所有文章除特別声明外，均采用
                    <a href="https://creativecommons.org/licenses/by/4.0/deed.zh" rel="external nofollow noreferrer" target="_blank">CC BY 4.0</a>
                    许可协议。转载请注明来源
                    <a href="/blog/about" target="_blank">xmxe</a>
                    !
                </span>
            </div>
        
    </div>

    <script async defer>
      document.addEventListener("copy", function (e) {
        let toastHTML = '<span>复制成功，请遵循本文的转载规则</span><button class="btn-flat toast-action" onclick="navToReprintStatement()" style="font-size: smaller">查看</a>';
        M.toast({html: toastHTML})
      });

      function navToReprintStatement() {
        $("html, body").animate({scrollTop: $("#reprint-statement").offset().top - 80}, 800);
      }
    </script>



            <div class="tag_share" style="display: block;">
                <div class="post-meta__tag-list" style="display: inline-block;">
                    
                        <div class="article-tag">
                            
                                <a href="/blog/tags/%E4%BB%A3%E7%A0%81%E5%AE%9E%E6%88%98/">
                                    <span class="chip bg-color">代码实战</span>
                                </a>
                            
                        </div>
                    
                </div>
                <div class="post_share" style="zoom: 80%; width: fit-content; display: inline-block; float: right; margin: -0.15rem 0;">
                    <link rel="stylesheet" type="text/css" href="/blog/libs/share/css/share.min.css">
<div id="article-share">

    
    <div class="social-share" data-sites="qq,qzone,wechat,weibo,douban" data-wechat-qrcode-helper="<p>微信扫一扫即可分享！</p>"></div>
    <script src="/blog/libs/share/js/social-share.min.js"></script>
    

    

</div>

                </div>
            </div>
            
                <style>
    #reward {
        margin: 40px 0;
        text-align: center;
    }

    #reward .reward-link {
        font-size: 1.4rem;
        line-height: 38px;
    }

    #reward .btn-floating:hover {
        box-shadow: 0 6px 12px rgba(0, 0, 0, 0.2), 0 5px 15px rgba(0, 0, 0, 0.2);
    }

    #rewardModal {
        width: 320px;
        height: 350px;
    }

    #rewardModal .reward-title {
        margin: 15px auto;
        padding-bottom: 5px;
    }

    #rewardModal .modal-content {
        padding: 10px;
    }

    #rewardModal .close {
        position: absolute;
        right: 15px;
        top: 15px;
        color: rgba(0, 0, 0, 0.5);
        font-size: 1.3rem;
        line-height: 20px;
        cursor: pointer;
    }

    #rewardModal .close:hover {
        color: #ef5350;
        transform: scale(1.3);
        -moz-transform:scale(1.3);
        -webkit-transform:scale(1.3);
        -o-transform:scale(1.3);
    }

    #rewardModal .reward-tabs {
        margin: 0 auto;
        width: 210px;
    }

    .reward-tabs .tabs {
        height: 38px;
        margin: 10px auto;
        padding-left: 0;
    }

    .reward-content ul {
        padding-left: 0 !important;
    }

    .reward-tabs .tabs .tab {
        height: 38px;
        line-height: 38px;
    }

    .reward-tabs .tab a {
        color: #fff;
        background-color: #ccc;
    }

    .reward-tabs .tab a:hover {
        background-color: #ccc;
        color: #fff;
    }

    .reward-tabs .wechat-tab .active {
        color: #fff !important;
        background-color: #22AB38 !important;
    }

    .reward-tabs .alipay-tab .active {
        color: #fff !important;
        background-color: #019FE8 !important;
    }

    .reward-tabs .reward-img {
        width: 210px;
        height: 210px;
    }
</style>

<div id="reward">
    <a href="#rewardModal" class="reward-link modal-trigger btn-floating btn-medium waves-effect waves-light red">赏</a>

    <!-- Modal Structure -->
    <div id="rewardModal" class="modal">
        <div class="modal-content">
            <a class="close modal-close"><i class="fas fa-times"></i></a>
            <h4 class="reward-title">你的赏识是我前进的动力</h4>
            <div class="reward-content">
                <div class="reward-tabs">
                    <ul class="tabs row">
                        <li class="tab col s6 alipay-tab waves-effect waves-light"><a href="#alipay">支付宝</a></li>
                        <li class="tab col s6 wechat-tab waves-effect waves-light"><a href="#wechat">微 信</a></li>
                    </ul>
                    <div id="alipay">
                        
                            <img src="/blog/medias/reward/alipay.jpg" class="reward-img" alt="支付宝打赏二维码">
                        
                    </div>
                    <div id="wechat">
                        
                            <img src="/blog/medias/reward/wechat.jpg" class="reward-img" alt="微信打赏二维码">
                        
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    $(function () {
        $('.tabs').tabs();
    });
</script>

            
        </div>
    </div>

    

    

    

    

    

    

    

    

<article id="prenext-posts" class="prev-next articles">
    <div class="row article-row">
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge left-badge text-color">
                <i class="fas fa-chevron-left"></i>&nbsp;上一篇</div>
            <div class="card">
                <a href="/blog/posts/4ab442c90ff9/">
                    <div class="card-image">
                        
                        <img src="https://pic1.zhimg.com/v2-bdccba68ad2e37f6efc96a15f7897e2d.jpg" class="responsive-img" alt="CSS相关">
                        
                        <span class="card-title">CSS相关</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            居中&lt;!-- div居中,需要设置宽度-->
&lt;div style="margin : 0 auto;width:80%">&lt;/div>
&lt;!-- div里面的内容居中-->
&lt;div style="margi
                        

                    </div>
                    <div class="publish-info">
                        <span class="publish-date">
                            <!--
                            <i class="far fa-clock fa-fw icon-date"></i>2023-04-03
                            -->

                            
                                <i class="fas fa-user fa-fw"></i>
                                <a href="/blog/about" >
                                    xmxe
                                </a>
                            
                        </span>
                        <span class="publish-author">
                            
                                <i class="fas fa-bookmark fa-fw icon-category"></i>
                                
                                    <a href="/blog/categories/CSS/" class="post-category">
                                        CSS
                                    </a>
                                
                            
                                
                                
                                <a href="/blog/tags/%E4%BB%A3%E7%A0%81%E5%AE%9E%E6%88%98/">
                                    <span class="chip bg-color">代码实战</span>
                                </a>
                                
                                
                            

                        </span>
                    </div>
                </div>
                
            </div>
        </div>
        
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge right-badge text-color">
                下一篇&nbsp;<i class="fas fa-chevron-right"></i>
            </div>
            <div class="card">
                <a href="/blog/posts/c83e06a22e1f/">
                    <div class="card-image">
                        
                        <img src="https://pic1.zhimg.com/v2-2bc1a9883960ccf43a0f4c643178c4c3_1440w.jpg" class="responsive-img" alt="Java类加载">
                        
                        <span class="card-title">Java类加载</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            类文件结构详解回顾一下字节码
在Java中，JVM可以理解的代码就叫做字节码（即扩展名为.class的文件），它不面向任何特定的处理器，只面向虚拟机。Java语言通过字节码的方式，在一定程度上解决了传统解释型语言执行效率低的问题，同时又保留
                        
                        
                    </div>
                    <div class="publish-info">
                        <span class="publish-date">
                            <!--
                            <i class="far fa-clock fa-fw icon-date"></i>2023-03-21
                            -->
                            
                                <i class="fas fa-user fa-fw"></i>
                                <a href="/blog/about" >
                                    xmxe
                                </a>
                            
                        </span>
                        <span class="publish-author">
                            
                                <i class="fas fa-bookmark fa-fw icon-category"></i>
                                
                                    <a href="/blog/categories/Java/" class="post-category">
                                        Java
                                    </a>
                                
                            
                        </span>
                    </div>
                </div>
                
            </div>
        </div>
        
    </div>
</article>

</div>



<!-- 代码块功能依赖 -->
<script type="text/javascript" src="/blog/libs/codeBlock/codeBlockFuction.js"></script>

<!-- 代码语言 -->

<script type="text/javascript" src="/blog/libs/codeBlock/codeLang.js"></script>


<!-- 代码块复制 -->

<script type="text/javascript" src="/blog/libs/codeBlock/codeCopy.js"></script>


<!-- 代码块收缩 -->

<script type="text/javascript" src="/blog/libs/codeBlock/codeShrink.js"></script>


    </div>
    <div id="toc-aside" class="expanded col l3 hide-on-med-and-down">
        <div class="toc-widget card">
            <div class="toc-title"><i class="far fa-list-alt"></i>&nbsp;&nbsp;目录</div>
            <div id="toc-content"></div>
        </div>
    </div>
</div>

<!-- TOC 悬浮按钮. -->

<div id="floating-toc-btn" class="hide-on-med-and-down">
    <a class="btn-floating btn-large bg-color">
        <i class="fas fa-list-ul"></i>
    </a>
</div>


<script src="/blog/libs/tocbot/tocbot.min.js"></script>
<script>
    $(function () {
        tocbot.init({
            tocSelector: '#toc-content',
            contentSelector: '#articleContent',
            headingsOffset: -($(window).height() * 0.4 - 45),
            collapseDepth: Number('0'),
            headingSelector: 'h1, h2, h3, h4, h5, h6'
        });

        // modify the toc link href to support Chinese.
        let i = 0;
        let tocHeading = 'toc-heading-';
        $('#toc-content a').each(function () {
            $(this).attr('href', '#' + tocHeading + (++i));
        });

        // modify the heading title id to support Chinese.
        i = 0;
        $('#articleContent').children('h1, h2, h3, h4, h5, h6').each(function () {
            $(this).attr('id', tocHeading + (++i));
        });

        // Set scroll toc fixed.
        let tocHeight = parseInt($(window).height() * 0.4 - 64);
        let $tocWidget = $('.toc-widget');
        $(window).scroll(function () {
            let scroll = $(window).scrollTop();
            /* add post toc fixed. */
            if (scroll > tocHeight) {
                $tocWidget.addClass('toc-fixed');
            } else {
                $tocWidget.removeClass('toc-fixed');
            }
        });

        
        /* 修复文章卡片 div 的宽度. */
        let fixPostCardWidth = function (srcId, targetId) {
            let srcDiv = $('#' + srcId);
            if (srcDiv.length === 0) {
                return;
            }

            let w = srcDiv.width();
            if (w >= 450) {
                w = w + 21;
            } else if (w >= 350 && w < 450) {
                w = w + 18;
            } else if (w >= 300 && w < 350) {
                w = w + 16;
            } else {
                w = w + 14;
            }
            $('#' + targetId).width(w);
        };

        // 切换TOC目录展开收缩的相关操作.
        const expandedClass = 'expanded';
        let $tocAside = $('#toc-aside');
        let $mainContent = $('#main-content');
        $('#floating-toc-btn .btn-floating').click(function () {
            if ($tocAside.hasClass(expandedClass)) {
                $tocAside.removeClass(expandedClass).hide();
                $mainContent.removeClass('l9');
            } else {
                $tocAside.addClass(expandedClass).show();
                $mainContent.addClass('l9');
            }
            fixPostCardWidth('artDetail', 'prenext-posts');
        });
        
    });
</script>

    

</main>




    <footer class="page-footer bg-color">
    
        <link rel="stylesheet" href="/blog/libs/aplayer/APlayer.min.css">
<style>
    .aplayer .aplayer-lrc p {
        
        display: none;
        
        font-size: 12px;
        font-weight: 700;
        line-height: 16px !important;
    }

    .aplayer .aplayer-lrc p.aplayer-lrc-current {
        
        display: none;
        
        font-size: 15px;
        color: #42b983;
    }

    
    .aplayer.aplayer-fixed.aplayer-narrow .aplayer-body {
        left: -66px !important;
    }

    .aplayer.aplayer-fixed.aplayer-narrow .aplayer-body:hover {
        left: 0px !important;
    }

    
</style>
<div class="">
    
    <div class="row">
        <meting-js class="col l8 offset-l2 m10 offset-m1 s12"
                   server="netease"
                   type="song"
                   id="569200213"
                   fixed='true'
                   autoplay='false'
                   theme='#42b983'
                   loop='all'
                   order='random'
                   preload='auto'
                   volume='0.7'
                   list-folded='true'
        >
        </meting-js>
    </div>
</div>

<script src="/blog/libs/aplayer/APlayer.min.js"></script>
<!-- <script src="https://cdn.jsdelivr.net/npm/meting@2/dist/Meting.min.js"></script> -->

    
    <div class="container row center-align" style="margin-bottom: 0px !important;">
        <div class="col s12 m8 l8 copy-right">
            Copyright&nbsp;&copy;
            
            
                <span id="year">2022-2025
                </span>
            
            

            <a href="/blog/about" target="_blank">
                xmxe
            </a>
            |&nbsp;Powered by&nbsp;
            <a href="https://hexo.io/" target="_blank">Hexo</a>
            |&nbsp;Theme&nbsp;
            <a href="https://github.com/blinkfox/hexo-theme-matery" target="_blank">Matery</a>
            <br>

            
            
            
            
            
            

            
            <br>

            
            <br>

            
        </div>
        <div class="col s12 m4 l4 social-link2 ">
    <a href="https://github.com/xmxe" class="tooltipped" target="_blank" data-tooltip="GitHub" data-position="top" data-delay="50">
        <i class="fab fa-github"></i>
    </a>



    <a href="https://gitee.com/xmxe" class="tooltipped" target="_blank" data-tooltip="码云" data-position="top" data-delay="50">
        <svg width="19" height="19" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" style="position: relative; top: 2px; left: 0.5px;">
            <path d="M512 1024C230.4 1024 0 793.6 0 512S230.4 0 512 0s512 230.4 512 512-230.4 512-512 512z m259.2-569.6H480c-12.8 0-25.6 12.8-25.6 25.6v64c0 12.8 12.8 25.6 25.6 25.6h176c12.8 0 25.6 12.8 25.6 25.6v12.8c0 41.6-35.2 76.8-76.8 76.8h-240c-12.8 0-25.6-12.8-25.6-25.6V416c0-41.6 35.2-76.8 76.8-76.8h355.2c12.8 0 25.6-12.8 25.6-25.6v-64c0-12.8-12.8-25.6-25.6-25.6H416c-105.6 0-188.8 86.4-188.8 188.8V768c0 12.8 12.8 25.6 25.6 25.6h374.4c92.8 0 169.6-76.8 169.6-169.6v-144c0-12.8-12.8-25.6-25.6-25.6z" fill="#fff">
            </path>
        </svg>
    </a>

















    
        
          <a href="/blog/download" class="tooltipped" target="_blank" data-tooltip="下载" data-position="top" data-delay="50">
            <i class="fas fa-download"></i>
          </a>
        
    



    <style>
  .mobiledevice {
    display: none !important;
  }

  footer .wechat_qrcode {
    position: fixed;
  }

  /*微信二维码*/
  .wechat_qrcode {
    position: absolute;
    margin-left: 10px;
    bottom: 10px;
    background: url("/blog/medias/xcx.png");
    zoom:40%;
  }

  .wechat:hover .wechat_qrcode {
    width: 430px;
    height: 430px;
    animation: move 0.4s linear 1 normal;
  }

  @keyframes move {
    0% {
      transform: translate(100px, 0);
      opacity: 0;
    }
    50% {
      transform: translate(50px, 0);
      opacity: 0.5;
    }
    100% {
      transform: translate(0, 0);
      opacity: 1;
    }
  }

  @media only screen and (max-width: 601px) {
    .wechat {
      display: none !important;
    }
    .mobiledevice {
      display: inline-block !important;
    }
  }
</style>

<a href="javascript:;" class="wechat" data-position="top" data-delay="50">
  <i class="fab fa-weixin"></i>
  <img class="wechat_qrcode" />
</a>

<a
  href="javascript:;"
  class="tooltipped mobiledevice"
  data-tooltip="微信: 464817304"
  data-position="top"
  data-delay="50"
>
  <i class="fab fa-weixin"></i>
</a>

</div>
    </div>
</footer>

<div class="progress-bar"></div>


    <!-- 搜索遮罩框 -->
<div id="searchModal" class="modal">
    <div class="modal-content">
        <div class="search-header">
            <span class="title"><i class="fas fa-search"></i>&nbsp;&nbsp;搜索</span>
            <input type="search" id="searchInput" name="s" placeholder="请输入搜索的关键字"
                   class="search-input">
        </div>
        <div id="searchResult"></div>
    </div>
</div>

<script type="text/javascript">
$(function () {
    var searchFunc = function (path, search_id, content_id) {
        'use strict';
        $.ajax({
            url: path,
            dataType: "xml",
            success: function (xmlResponse) {
                // get the contents from search data
                var datas = $("entry", xmlResponse).map(function () {
                    return {
                        title: $("title", this).text(),
                        content: $("content", this).text(),
                        url: $("url", this).text()
                    };
                }).get();
                var $input = document.getElementById(search_id);
                var $resultContent = document.getElementById(content_id);
                $input.addEventListener('input', function () {
                    var str = '<ul class=\"search-result-list\">';
                    var keywords = this.value.trim().toLowerCase().split(/[\s\-]+/);
                    $resultContent.innerHTML = "";
                    if (this.value.trim().length <= 0) {
                        return;
                    }
                    // perform local searching
                    datas.forEach(function (data) {
                        var isMatch = true;
                        var data_title = data.title.trim().toLowerCase();
                        var data_content = data.content.trim().replace(/<[^>]+>/g, "").toLowerCase();
                        var data_url = data.url;
                        data_url = data_url.indexOf('/') === 0 ? data.url : '/' + data_url;
                        var index_title = -1;
                        var index_content = -1;
                        var first_occur = -1;
                        // only match artiles with not empty titles and contents
                        if (data_title !== '' && data_content !== '') {
                            keywords.forEach(function (keyword, i) {
                                index_title = data_title.indexOf(keyword);
                                index_content = data_content.indexOf(keyword);
                                if (index_title < 0 && index_content < 0) {
                                    isMatch = false;
                                } else {
                                    if (index_content < 0) {
                                        index_content = 0;
                                    }
                                    if (i === 0) {
                                        first_occur = index_content;
                                    }
                                }
                            });
                        }
                        // show search results
                        if (isMatch) {
                            str += "<li><a href='" + data_url + "' class='search-result-title'>" + data_title + "</a>";
                            var content = data.content.trim().replace(/<[^>]+>/g, "");
                            if (first_occur >= 0) {
                                // cut out 100 characters
                                var start = first_occur - 20;
                                var end = first_occur + 80;
                                if (start < 0) {
                                    start = 0;
                                }
                                if (start === 0) {
                                    end = 100;
                                }
                                if (end > content.length) {
                                    end = content.length;
                                }
                                var match_content = content.substr(start, end);
                                // highlight all keywords
                                keywords.forEach(function (keyword) {
                                    var regS = new RegExp(keyword, "gi");
                                    match_content = match_content.replace(regS, "<em class=\"search-keyword\">" + keyword + "</em>");
                                });

                                str += "<p class=\"search-result\">" + match_content + "...</p>"
                            }
                            str += "</li>";
                        }
                    });
                    str += "</ul>";
                    $resultContent.innerHTML = str;
                });
            }
        });
    };

    searchFunc('/blog/search.xml', 'searchInput', 'searchResult');
});
</script>

    <!-- 回到顶部按钮 -->
<div id="backTop" class="top-scroll">
    <a class="btn-floating btn-large waves-effect waves-light" href="#!">
        <i class="fas fa-arrow-up"></i>
    </a>
</div>

    <div class="stars-con">
  <div id="stars"></div>
  <div id="stars2"></div>
  <div id="stars3"></div>  
</div>

<!-- 白天和黑夜主题 -->



<script>
  function switchNightMode() {
    
      setTimeout(function () {
        $('body').hasClass('DarkMode') 
        ? ($('body').removeClass('DarkMode'), localStorage.setItem('isDark', '0'), $('#sum-moon-icon').removeClass("fa-sun").addClass('fa-moon')) 
        : ($('body').addClass('DarkMode'), localStorage.setItem('isDark', '1'), $('#sum-moon-icon').addClass("fa-sun").removeClass('fa-moon')),
          
        setTimeout(function () {
          $('.Cuteen_DarkSky').fadeOut(1e3, function () {
            $(this).remove()
          })
        }, 2e3)
      })
  }
</script>
    
    
    <script>
        /* 模式判断 */
        if (localStorage.getItem('isDark') === '1') {
            document.body.classList.add('DarkMode');
            $('#sum-moon-icon').addClass("fa-sun").removeClass('fa-moon')
        } else {
            document.body.classList.remove('DarkMode');
            $('#sum-moon-icon').removeClass("fa-sun").addClass('fa-moon')
        }
    </script>

    <script src="/blog/libs/materialize/materialize.min.js"></script>
    <script src="/blog/libs/masonry/masonry.pkgd.min.js"></script>
    <script src="/blog/libs/aos/aos.js"></script>
    <script src="/blog/libs/scrollprogress/scrollProgress.min.js"></script>
    <script src="/blog/libs/lightGallery/js/lightgallery-all.min.js"></script>
    <script src="/blog/js/matery.js"></script>

    <!-- Baidu Analytics -->

    <!-- Baidu Push -->

<script>
    (function () {
        var bp = document.createElement('script');
        var curProtocol = window.location.protocol.split(':')[0];
        if (curProtocol === 'https') {
            bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
        } else {
            bp.src = 'http://push.zhanzhang.baidu.com/push.js';
        }
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(bp, s);
    })();
</script>

    
    

    

    

	
    

    

    
    <script type="text/javascript" src="/blog/libs/background/ribbon-dynamic.js" async="async"></script>
    

    

    <!-- 冒泡 -->
    
    <script type="text/javascript">
        // 只在桌面版网页启用特效
        // var windowWidth = $(window).width();
        
            document.write('<script type="text/javascript" src="/blog/libs/others/bubleAll.js"><\/script>');
        
        
    </script>
    

    <!-- 弹出文字 -->
    

</body>

</html>
